<template>
  <dtDialog
    title="企业认证信息"
    :visible.sync="dialogVisible"
    :lock-scroll="false"
    :append-to-body="true"
    :is-loading="loading"
    :width="'1000px'"
    v-loading="dataLoading"
    @closeDialog="onModalClosed"
    @comfirmBtn="onSubmit()"
  >
    <el-form
      ref="form"
      slot="content"
      label-width="170px"
      :model="form"
      :rules="rules"
      style="position: relative;"
    >
      <p style="text-align: right; margin-block-start: 0;">当前认证状态：{{ stateMap[state] }}</p>
      <el-row>
        <el-col :span="12">
          <el-form-item label="企业名称" prop="enterpriseName">
            <el-input
              v-model.trim="form.enterpriseName"
              maxlength="30"
              placeholder="请输入企业名称"
              show-word-limit
              disabled
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="认证系统" prop="systemId">
            <el-select v-model.trim="form.systemId" placeholder="请选择认证系统" :disabled="isEdit"
                       @change="getTabPage(form.systemId)">
              <el-option v-for="sys in systemList" :key="sys.id" :label="sys.systemName"
                         :value="sys.systemId"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="统一社会信用代码" prop="socialCreditCode">
            <el-input
              v-model.trim="form.socialCreditCode"
              placeholder="请输入统一社会信用代码"
              disabled
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="校验等级" prop="chkLevel">
            <el-select v-model.trim="form.chkLevel" placeholder="请选择校验等级">
              <el-option label="强制校验" value="1"></el-option>
              <el-option label="提示预警" value="2"></el-option>
              <el-option label="无处理" value="3"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="税务登记号" prop="taxCode">
            <el-input
              v-model.trim="form.taxCode"
              placeholder="请输入税务登记号"
              disabled
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="法人姓名" prop="legalPersonName">
            <el-input
              v-model.trim="form.legalPersonName"
              placeholder="请输入法人姓名"
              disabled
            />
          </el-form-item>
        </el-col>
        <el-row>
          <el-col :span="12">
            <el-form-item label="法人身份证号" prop="legalPersonIdCard">
              <el-input
                v-model.trim="form.legalPersonIdCard"
                disabled
                placeholder="请输入法人身份证号"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="法人联系方式" prop="legalPersonPhone">
              <el-input
                v-model.trim="form.legalPersonPhone"
                placeholder="请输入法人联系方式"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="营业执照号" prop="licenseCode">
              <el-input
                v-model.trim="form.licenseCode"
                placeholder="请输入营业执照号"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="营业执照有效开始时间" prop="licenseStartTime">
              <el-date-picker
                v-model="form.licenseStartTime"
                type="date"
                value-format="yyyy-MM-dd HH:mm:ss"
                format="yyyy-MM-dd"
                style="width: 100%"
                placeholder="请选择营业执照有效开始时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="营业执照有效结束时间" prop="licenseEndTime">
              <el-date-picker
                v-model="form.licenseEndTime"
                type="date"
                value-format="yyyy-MM-dd HH:mm:ss"
                format="yyyy-MM-dd"
                style="width: 100%"
                placeholder="请选择营业执照有效结束时间"
              >
              <!-- :picker-options="endTimeOptions" -->
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </el-row>
      <div class="photo-box">
        <el-form-item label="营业执照" prop="fileList">
          <dt-upload v-model="form.fileList" :fileSize="50" :list-type="'picture-card'"
                     @input="handleInput(form.fileList)" />
        </el-form-item>
      </div>
    </el-form>
    <el-row class="other-info">
      <el-col :span="24">
        <h2>其他企业认证信息</h2>
      </el-col>
      <el-col :span="24">
        <el-tabs type="border-card" :stretch="true" v-model="action">
          <el-tab-pane label="法人身份认证" v-if="whileList.includes(1)" name="1">
            <id-card ref="idCard" :idCardNumber="form.legalPersonIdCard" />
          </el-tab-pane>
          <el-tab-pane label="许可认证" v-if="whileList.includes(2)" name="2">
            <license-card ref="licenseCard" />
          </el-tab-pane>
          <el-tab-pane label="银行卡认证" v-if="whileList.includes(3)" name="3">
            <bank-card ref="bankCard" />
          </el-tab-pane>
          <el-tab-pane label="授权书认证" v-if="whileList.includes(4)" name="4">
            <empower-card ref="empowerCard" />
          </el-tab-pane>
          <el-tab-pane label="附件" name="5">
            <annex-file ref="annexFile" />
          </el-tab-pane>
        </el-tabs>
      </el-col>
    </el-row>
  </dtDialog>
</template>

<script>
import idCard from './informationCompo/idCard'
import licenseCard from './informationCompo/licenseCard'
import bankCard from './informationCompo/bankCard'
import empowerCard from './informationCompo/empowerCard'
import annexFile from './informationCompo/annexFile'
import { getSupplyDetail, getSupplyBaseDetail, recognition, getTabPage, addEnterpriseSupply, editEnterpriseSupply } from '@/api/information/index'
import { getSystemInfoList } from '@/api/problemPreset/index'
import { checkPhone } from '@/framework/utils/validate'
import { handleImage, formatDate } from '../utils'

const STATE_MAP = {
  0: '未认证',
  1: '认证中',
  2: '已认证'
}
const TAB_LIST = {
  1: '法人身份认证',
  2: '许可认证',
  3: '银行卡认证',
  4: '授权书认证'
}

let LICENSE = {} // 存储校验信息
let validateSts = []
let validateMsg = ''
export default {
  components: {
    idCard,
    licenseCard,
    bankCard,
    empowerCard,
    annexFile
  },
  data() {
    const validatePhone = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入手机号/电话'))
      } else if (!checkPhone(value)) {
        callback(new Error('请输入合法的手机号/电话'))
      } else {
        callback()
      }
    }
    return {
      stateMap: STATE_MAP,
      dialogVisible: false,
      action: '5',
      loading: false,
      buttonLoading: false,
      form: {
        enterpriseName: '',
        systemId: '',
        socialCreditCode: '',
        chkLevel: '',
        taxCode: '',
        legalPersonName: '',
        legalPersonIdCard: '',
        legalPersonPhone: '',
        licenseCode: '',
        licenseStartTime: '',
        licenseEndTime: '',
        fileList: []
      },
      rules: {
        systemId: [{ required: true, trigger: 'change', message: '请选择认证系统' }],
        chkLevel: [{ required: true, trigger: 'change', message: '请选择校验等级' }],
        legalPersonPhone: [{ required: true, trigger: 'blur', validator: validatePhone }],
        licenseCode: [{ required: true, trigger: 'blur', message: '请输入营业执照号' }],
        licenseStartTime: [{ required: true, trigger: 'change', message: '请选择营业执照有效开始时间' }],
        licenseEndTime: [{ required: true, trigger: 'change', message: '请选择营业执照有效结束时间' }],
        fileList: [{ required: true, trigger: 'change', message: '请上传营业执照' }]
      },
      whileList: [],
      systemList: [],
      enterpriseId: '',
      state: 0,
      dataLoading: false,
      isEdit: false
    }
  },
  mounted() {
    getSystemInfoList().then((res) => {
      this.systemList = res.data
    })
  },
  methods: {
    handleInput(val) {
      recognition({
        fileId: val[0].fileId,
        recognitionType: 3
      }).then((res) => {
        const { licenseCode, licenseEndTime, licenseStartTime, socialCreditCode } = res.data
        LICENSE.licenseCode = licenseCode
        LICENSE.licenseEndTime = formatDate(licenseEndTime)
        LICENSE.licenseStartTime = formatDate(licenseStartTime)
        LICENSE.socialCreditCode = socialCreditCode
        if (LICENSE.licenseStartTime) {
          this.form.licenseStartTime = LICENSE.licenseStartTime
        }
        if (LICENSE.licenseEndTime) {
          this.form.licenseEndTime = LICENSE.licenseEndTime
        }
      })
    },
    open(data, type) {
      this.dialogVisible = true
      this.enterpriseId = data.enterpriseId
      this.state = data.state || 0
      this.dataLoading = true
      this.isEdit = type == 1
      getSupplyDetail({
        enterpriseId: data.enterpriseId,
        systemId: data.systemId || ''
      }).then((res) => {
        this.form = res.data
        this.form.systemId = data.systemId
        this.state = data.state || 0
        this.echoData(res.data)
        const list = this.form.fileInfoList.filter((item) => item.fileType == '9')
        this.$refs.annexFile.echoData(list)
      }).finally(() => {
        this.dataLoading = false
      })
    },
    echoData(data) {
      if (data.systemId) {
        this.getTabPage(data.systemId, true)
      }
      const obj = data.fileInfoList.find((item) => item.fileType == '0')
      if (obj) {
        this.form.fileList = obj ? handleImage(obj) : []
      }
      this.$nextTick(() => {
        this.$refs.form.clearValidate()
      })
    },
    onModalClosed() {
      this.initModal()
      this.buttonLoading = false
      this.loading = false
      this.enterpriseId = ''
      this.state = 0
      this.isEdit = false
      this.action = '5'
      this.whileList = []
      LICENSE = {}
      validateSts = []
      this.form.fileList = []
      if (this.whileList.includes(1)) {
        this.$refs.idCard.init()
      }
      if (this.whileList.includes(2)) {
        this.$refs.licenseCard.init()
      }
      if (this.whileList.includes(3)) {
        this.$refs.bankCard.init()
      }
      if (this.whileList.includes(4)) {
        this.$refs.empowerCard.init()
      }
      this.$refs.annexFile.init()
    },
    initModal() {
      this.$refs.form.resetFields()
      this.form = {}
    },
    getTabPage(systemId, type) {
      getTabPage({ systemId }).then((res) => {
        this.whileList = res.data.map((num) => +num)
        this.$nextTick(() => {
          const action = this.whileList.length > 0 ? this.whileList[0] : 5
          this.action = String(action)
        })
        this.echoTabData()
      })
    },
    echoTabData() {
      this.$nextTick(() => {
        if (this.whileList.includes(1) && this.form.legalPresonList.length > 0) {
          this.$refs.idCard.echoData(this.form.legalPresonList)
        }
        if (this.whileList.includes(2) && this.form.permitList.length > 0) {
          this.$refs.licenseCard.echoData(this.form.permitList)
        }
        if (this.whileList.includes(3) && this.form.bankList.length > 0) {
          this.$refs.bankCard.echoData(this.form.bankList)
        }
        if (this.whileList.includes(4) && this.form.auth) {
          this.$refs.empowerCard.echoData(this.form.auth)
        }
        const list = this.form.fileInfoList.filter((item) => item.fileType == '9')
        this.$refs.annexFile.echoData(list)
      })
    },
    // 点击提交
    onSubmit() {
      let data = {}
      let legalPresonRequestList = []
      let permitRequestList = []
      let bankRequestList = []
      let authRequest = {}
      let fileInfoRequestList = []
      this.$refs.form.validate((result) => {
        validateSts.push(result)
      })
      this.loading = true
      if (this.whileList.includes(1)) {
        this.validateForm('idCard', 1)
        legalPresonRequestList = this.setIdCardData()
      } else {
        legalPresonRequestList = this.form.legalPresonList
      }
      if (this.whileList.includes(2)) {
        this.validateForm('licenseCard', 2)
        permitRequestList = this.setlicenseCardData()
      } else {
        permitRequestList = this.form.permitList
      }
      if (this.whileList.includes(3)) {
        this.validateForm('bankCard', 3)
        bankRequestList = this.setBankCardData()
      } else {
        bankRequestList = this.form.bankList
      }
      if (this.whileList.includes(4)) {
        // this.validateForm('empowerCard', 4)
        authRequest = this.setEmpowerCardData()
      } else {
        authRequest = this.form.auth
      }
      fileInfoRequestList = this.setAnnexFileData()
      const dateTime = new Date(this.form.licenseEndTime).getTime()
      const nowTime = new Date().getTime()
      /**
       * 测试暂时去除校验
       * lyw 20240307
       */
      // if (LICENSE.licenseCode !== this.form.licenseCode) {
      //   this.$message.warning('上传的营业执照号与企业查询的营业执照号不同，不允许认证')
      //   this.loading = false
      //   return
      // }
      // if (nowTime > dateTime && dateTime) {
      //   this.$message.warning('营业执照有效期的结束时间应该在当前时间之后')
      //   this.loading = false
      //   return
      // }
      const sts = validateSts.every((item) => item)
      if (sts) {
        data = { ...this.form, legalPresonRequestList, permitRequestList, bankRequestList, authRequest, fileInfoRequestList }
        this.submitData(data)
      } else {
        this.loading = false
        if (validateMsg) {
          validateMsg = validateMsg.substring(0, validateMsg.length - 1)
          setTimeout(() => {
            this.$message.warning(`${validateMsg}下存在未填写的必填项，不允许提交`)
            validateSts = []
            validateMsg = ''
          }, 200)
        } else {
          validateSts = []
          validateMsg = ''
        }
      }
    },
    submitData(data) {
      if (this.isEdit) {
        editEnterpriseSupply(data).then((res) => {
          this.$message.success(res.message)
          this.loading = false
          this.dialogVisible = false
        }).catch(() => {
          this.loading = false
        })
      } else {
        addEnterpriseSupply(data).then((res) => {
          this.$message.success(res.message)
          this.loading = false
          this.dialogVisible = false
        }).catch(() => {
          this.loading = false
        })
      }
    },
    validateForm(dom, i) {
      const validateResult = this.$refs[dom].validate()
      validateSts.push(validateResult)
      if (!validateResult && this.action != i) {
        validateMsg += `${TAB_LIST[i]}、`
      }
    },
    setIdCardData() {
      const { effectiveStartDate, effectiveEndDate, frontList, oppositeList } = this.$refs.idCard.submit()
      return [
        {
          enterpriseId: this.form.enterpriseId,
          type: 2,
          fileId: frontList[0] && frontList[0].fileId,
          effectiveStartDate,
          effectiveEndDate
        },
        {
          enterpriseId: this.form.enterpriseId,
          type: 1,
          fileId: oppositeList[0] && oppositeList[0].fileId,
          effectiveStartDate,
          effectiveEndDate
        }
      ]
    },
    setlicenseCardData() {
      return this.$refs.licenseCard.submit().map((item) => {
        item.enterpriseId = this.form.enterpriseId
        item.fileInfoRequestList = item.fileInfoRequestList.map((file) => {
          return {
            enterpriseId: this.form.enterpriseId,
            fileType: '2',
            fileId: file.id,
            fileName: file.name,
            ...file
          }
        })
        return item
      })
    },
    setBankCardData() {
      return this.$refs.bankCard.submit().map((item) => {
        item.enterpriseId = this.form.enterpriseId
        item.fileId = item.fileList.length > 0 && item.fileList[0].fileId
        item.fileInfoRequestList = item.fileInfoRequestList.map((file) => {
          return {
            enterpriseId: this.form.enterpriseId,
            fileType: '3',
            fileId: file.id,
            fileName: file.name,
            ...file
          }
        })
        return item
      })
    },
    setEmpowerCardData() {
      const authRequest = this.$refs.empowerCard.submit()
      authRequest.fileInfoRequestList = authRequest.fileInfoRequestList.map((file) => {
        return {
          enterpriseId: this.form.enterpriseId,
          fileType: '4',
          fileId: file.fileId,
          fileName: file.name,
          ...file
        }
      })
      return authRequest
    },
    setAnnexFileData() {
      const annexFileList = this.$refs.annexFile.submit().map((item, i) => {
        item.fileType = '9'
        item.fileId = item.id
        item.enterpriseId = this.form.enterpriseId
        item.fileName = item.name
        return item
      })
      let arr = []
      if (this.form.fileList) {
        arr = this.form.fileList.map((item) => {
          item.id = item.fileId
          item.enterpriseId = this.form.enterpriseId
          item.fileType = '0'
          item.fileName = item.name
          return item
        })
      }
      return [...arr, ...annexFileList]
    }
  }
}
</script>

<style lang="scss" scoped>
.el-form-item {
  position: relative;
  z-index: 2;
}
.el-select {
  width: 100%;
}
.photo-box {
  position: absolute;
  right: 5.3%;
  top: 42%;
  text-align: center;
  .el-image {
    width: 240px;
    min-height: 200px;
    background-color: #f5f7fa;
  }
  .image-slot i {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    font-size: 24px;
  }
}
.image-slot {
  width: 240px;
  height: 240px;
  background-color: #0000;
}
</style>
